package com.cheng.user.util;

import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {

    private static final String secret = "demo-user";
    private static final Long expire = 7200000L;

    /**
     * 生成token
     * @param id 用户的id
     * @return
     */
    public static String createToken(Integer id){

        Map<String,Object> claims = new HashMap<>();
        claims.put("userid",id);
        JwtBuilder jwtBuilder = Jwts.builder()
                // 签发算法，秘钥为jwtToken
                .signWith(SignatureAlgorithm.HS256, secret)
                // body数据，要唯一，自行设置
                .setClaims(claims)
                // 设置签发时间
                .setIssuedAt(new Date())
                // 有效时间
                .setExpiration(new Date(System.currentTimeMillis() + expire));
        return jwtBuilder.compact();
    }

    /**
     * 解密token
     * @param token
     * @return
     */
    public static Integer checkToken(String token){
        Jwt parse = Jwts.parser().setSigningKey(secret).parse(token);
        Map<String, Object> body = (Map<String, Object>) parse.getBody();
        return (Integer) body.get("userid");
    }


}
